/*
 * Copyright 2021 Readium Foundation. All rights reserved.
 * Use of this source code is governed by the BSD-style license
 * available in the top-level LICENSE file of the project.
 */

package org.readium.r2.testapp.catalogs

import android.animation.ObjectAnimator
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.GestureDetector
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import android.widget.Switch
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.viewmodel.compose.viewModel
import org.readium.r2.testapp.R
import org.readium.r2.testapp.utils.launchWebBrowser
import org.readium.r2.testapp.web.Web
import timber.log.Timber

class WordBook : Fragment() {

    private val wordBookViewModel: WordBookViewModel by activityViewModels()

    private lateinit var webView: WebView

    private lateinit var entryView: TextView

    private lateinit var isMarked: Switch

    private lateinit var gestureDetector: GestureDetector

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.word_book, container, false)
        webView = view.findViewById(R.id.webView)
        entryView = view.findViewById(R.id.titleTextView)
        isMarked = view.findViewById(R.id.switch1)

        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        wordBookViewModel.nowWord.observe(viewLifecycleOwner) { word ->
            if (wordBookViewModel.wordList.value.isNullOrEmpty()) {
                val emptyHtmlData = "<html><body><h1>No words available</h1><p>Please add some words to the list.</p></body></html>"
                webView.loadData(emptyHtmlData, "text/html", "UTF-8")
            } else {
                word?.let {
                    val title = it.entry + "(" + (wordBookViewModel.currentIndex.value) + "/" + wordBookViewModel.wordList.value!!.size + ")"
                    entryView.text = title

                    isMarked.isChecked = it.isMarked

                    val htmlData = """
                        <!DOCTYPE html>
                        <html>
                        <head>
                            <link rel="stylesheet" type="text/css" href="file:///android_asset/dicts/sf_cb.css">
                        </head>
                        <body>
                            ${it.definition.substring(it.definition.indexOf("\\n") + 2)}
                        </body>
                        </html>
                    """

                    webView.loadDataWithBaseURL(null, htmlData, "text/html", "UTF-8", null)
                }
            }
        }

        // Set OnCheckedChangeListener for the Switch
        isMarked.setOnCheckedChangeListener { _, isChecked ->
            // Handle the switch toggle event
            if (isChecked) {

            } else {

            }
        }

        webView.setOnTouchListener { _, event ->
            gestureDetector.onTouchEvent(event)
            true
        }

        isMarked.setOnCheckedChangeListener { _, isChecked ->
            onCheckedChanged(isChecked)
        }

        // Initialize GestureDetector
        gestureDetector = GestureDetector(context, GestureListener())

        // Set touch listener on the root view
        view.setOnTouchListener { _, event ->
            gestureDetector.onTouchEvent(event)
            true
        }

        wordBookViewModel.updateWordList()
    }

    private inner class GestureListener : GestureDetector.SimpleOnGestureListener() {
        private val SWIPE_THRESHOLD = 100
        private val SWIPE_VELOCITY_THRESHOLD = 100

        override fun onFling(
            e1: MotionEvent?, e2: MotionEvent, velocityX: Float, velocityY: Float
        ): Boolean {
            if (e1 == null || e2 == null) return false
            val diffX = e2.x - e1.x
            val diffY = e2.y - e1.y
            if (Math.abs(diffX) > Math.abs(diffY)) {
                if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                    if (diffX > 0) {
                        onSwipeRight()
                    } else {
                        onSwipeLeft()
                    }
                    return true
                }
            }
            return false
        }

        override fun onScroll(
            e1: MotionEvent?, e2: MotionEvent, distanceX: Float, distanceY: Float
        ): Boolean {
            webView.scrollBy(0, distanceY.toInt())
            return true
        }
    }

    private fun onCheckedChanged(isChecked: Boolean) {
        // Handle the switch toggle event
        wordBookViewModel.markVocabulary(isChecked)
    }

    private fun onSwipeRight() {
        // Handle swipe right
        animateSwipe(webView, 100f)
        wordBookViewModel.indexBackward()
    }

    private fun onSwipeLeft() {
        // Handle swipe left
        animateSwipe(webView, -100f)
        wordBookViewModel.indexForward()
    }

    private fun animateSwipe(view: View, translationX: Float) {
        ObjectAnimator.ofFloat(view, "translationX", translationX, 0f).apply {
            duration = 300
            start()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        webView.destroy() // 清理 WebView
    }
}
